package com.lms.controller;


import com.lms.bean.Permission;
import com.lms.bean.Role;
import com.lms.bean.Type;
import com.lms.bean.User;
import com.lms.realm.LmsRealm;
import com.lms.service.PermissionService;
import com.lms.service.RoleService;
import com.lms.util.ResultUtils;
import com.lms.vo.RoleVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @RequestMapping("admin/role-list")
    public String toRoleList() {
        return "admin/role-list";
    }

    @RequestMapping("admin/role-input")
    @RequiresRoles("superadmin")
    public String toTypeInput(Long roleId, Model model) {
        if(-1==roleId){
            model.addAttribute("operation","添加角色");
            model.addAttribute("role",new Role());
        }else{
            model.addAttribute("operation","更新角色");
            Role role = roleService.findRoleById(roleId);
            model.addAttribute("role",role);
        }
        List<Permission> permissions=permissionService.findAll();
        model.addAttribute("permissions",permissions);
        return "admin/role-input";
    }

    @RequestMapping("save")
    @RequiresRoles("superadmin")
    public String save(@RequestParam("permissionIds") String permissionIds,
                       @RequestParam("roleId") Long roleId,
                       @RequestParam("rolename") String rolename
                        ){
        String[] pers = permissionIds.split(",");
        List<Long> ids = new ArrayList<>();
        for (String s : pers){
            ids.add(Long.valueOf(s));
        }
        Set<Permission> permissionSet=new HashSet<>();
        for(Long s:ids){
            permissionSet.add(permissionService.findById(s));
        }
        Role role=roleService.findRoleById(roleId);
        role.setPermissions(permissionSet);
        roleService.save(role);
      /*  RealmSecurityManager rsm = (RealmSecurityManager)SecurityUtils.getSecurityManager();
        LmsRealm realm = (LmsRealm)rsm.getRealms().iterator().next();
       // String realmName=realm.getName();
       // realm.clearCachedAuthorization();
        for(User user:role.getUserList()){
            reloadAuthorizing(realm,user.getUsername());
        }*/
        return "redirect:admin/role-list";
    }


    public static void reloadAuthorizing(LmsRealm lmsRealm,String username){
        Subject subject = SecurityUtils.getSubject();
        String realmName = subject.getPrincipals().getRealmNames().iterator().next();
        //第一个参数为用户名,第二个参数为realmName,test想要操作权限的用户
        SimplePrincipalCollection principals = new SimplePrincipalCollection(username,realmName);
        //new SimpleAuthenticationInfo(user,user.getPassword(),realmName);
        subject.runAs(principals);
        lmsRealm.getAuthorizationCache().remove(subject.getPrincipals());
        subject.releaseRunAs();
    }

    /**
     * @param pageFromLayUI  计数方式是 1,2,3,4...,n  默认为 1 ;
     *                       但是 Pageable.page 的计数方式是 0,1,2,3,...,n-1 默认为 0
     * @param limitFromLayUI 等于 Pageable.size
     * @return 能被 layUI 接受的 JSON, 格式为 { "code": 0, "msg": "OK", count": 14, "data":[{},{},{}] }
     */
    @RequestMapping("all")
    @ResponseBody
    public ResultUtils<RoleVO> findAll(@RequestParam("page") Integer pageFromLayUI,
                                       @RequestParam("limit") Integer limitFromLayUI) {
        //获取记录的总数，交给前端计算分页
        Long count = roleService.getTotalCount();
        //获取当前页的记录列表交给前端渲染,注意 layUI 和 pageable 关于 page 的计数差别
        List<RoleVO> data = roleService.findAll(pageFromLayUI - 1, limitFromLayUI);
        //返回JSON结果
        return ResultUtils.layUITable(count, data);
    }

    @RequestMapping("delete")
    @RequiresRoles("superadmin")
    public String delete(Long roleId){
        roleService.deleteById(roleId);
        return "redirect:admin/role-list";
    }

}